﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Project.Common.Upload;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace Project.WebAPI.Controllers
{
    /// <summary>
    /// 文件上传和下载
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class FilesController : ControllerBase
    {
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="path">文件名</param>
        /// <param name="saveName">保存在客户端时的默认文件名(需要带后缀名)，可以为空</param>
        /// <returns></returns>
        [HttpGet("{path}")]
        public IActionResult GetFiles(string path, string saveName = null)
        {
            // 获取文件的默认路径
            var file = Path.Combine(Directory.GetCurrentDirectory(),
                            "UploadFiles", path);
            // 客户都保存的名字
            if (string.IsNullOrEmpty(saveName))
                saveName = path;

            return PhysicalFile(file, "application/octet-stream", saveName);
        }

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="formcollection"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UpFile(IFormCollection formcollection)
        {

            try
            {
                var files = formcollection.Files;
                if (files != null && files.Any())
                {
                    var file = files[0];
                    string contentType = file.ContentType;
                    string fileExtention = Path.GetExtension(file.FileName); // 扩展名
                    string cdipath = Directory.GetCurrentDirectory();

                    string fileupName = Guid.NewGuid().ToString("d") + fileExtention;
                    string upfilePath = Path.Combine(cdipath + "/UploadFiles/", fileupName);
                    if (!System.IO.File.Exists(upfilePath))
                    {
                        using var Stream = System.IO.File.Create(upfilePath);
                    }
                    double count = await UpLoadFileStreamHelper.UploadWriteFileAsync(file.OpenReadStream(), upfilePath);
                    return Ok(new { Path = fileupName, Name = file.FileName });
                    //result.message = "上传成功！"; result.code = statuCode.success; result.data = $"上传的文件大小为:{count}MB";
                }
                return BadRequest("请选择文件");
            }
            catch (Exception ex)
            {
                return BadRequest(ex.Message);
            }


        }

    
       


        //[HttpPost, Route("UpFile03")]
        //public async Task<IActionResult> UpFile03([FromForm]IFormFile file)// 这里一定要加[FromForm]的特性，模型里面可以不用加
        //{

        //    string cdipath = Directory.GetCurrentDirectory();
        //    string fileOrginname = file.FileName;//新建文本文档.txt  原始的文件名称
        //    string fileExtention = Path.GetExtension(fileOrginname);
        //    string fileupName = Guid.NewGuid().ToString("d") + fileExtention;
        //    string upfilePath = Path.Combine(cdipath + "/myupfiles/", fileupName);
        //    try
        //    {
        //        bool flag = await UpLoadFileStreamHelper.UploadWriteFileAsync(file,upfilePath);

        //        return Ok( flag ? "上传成功" : "上传失败");
        //    }
        //    catch (Exception ex)
        //    {
        //        return BadRequest("上传异常,原因:" + ex.Message);
        //    }

        //}
    }
}
